﻿Imports System.Net
Imports System.Data
Imports System.Xml
Imports System.IO
Imports System.Text
Imports System.Windows.Controls
Imports Microsoft.Windows.Controls


Public Class ResultsWindow

    Private _resultsDS As DataSet
    Private _username As String
    Private _password As String
    Private _domain As String
    Private _url As String
    Private _startAt As String
    Private _countResults As String
    Private _SearchService As SearchService.QueryService
    Private _numTotalResults As String
    Private _intEndResultsShowing As Integer
    Private _wsQueryType As WSQueryType

    Public Property Username As String
        Get
            Return _username
        End Get
        Set(ByVal value As String)
            _username = value
        End Set
    End Property

    Public Property Password As String
        Get
            Return _password
        End Get
        Set(ByVal value As String)
            _password = value
        End Set
    End Property

    Public Property Domain As String
        Get
            Return _domain
        End Get
        Set(ByVal value As String)
            _domain = value
        End Set
    End Property

    Public Property WebserviceUrl As String
        Get
            Return _url
        End Get
        Set(ByVal value As String)
            _url = value
        End Set
    End Property

    Public Sub SetResultsWinProperties_Query(ByVal queryXml As String, ByVal resultsXmlString As String)

        'Set the query type for future queries
        _wsQueryType = WSQueryType.Query

        Dim queryXDoc As XDocument = XDocument.Load(New StringReader(queryXml))
        _startAt = queryXDoc.Element("QueryPacket").Element("Query").Element("Range").Element("StartAt").Value
        _countResults = queryXDoc.Element("QueryPacket").Element("Query").Element("Range").Element("Count").Value

        'Format the query
        Me.txtQuery.Text = queryXDoc.ToString()
        _query = queryXDoc.ToString()

        Dim tempFile As String = String.Empty
        tempFile = Path.ChangeExtension(Path.GetTempFileName(), "xml")

        Dim resultsXmlDoc As XDocument = XDocument.Load(New StringReader(resultsXmlString))
        resultsXmlDoc.Save(tempFile)

        'Navigate to the temporary file
        ieXML.Navigate(New Uri(tempFile))
        'Provide a text view of the xml
        Me.txtResultsXml.Text = resultsXmlDoc.ToString()

        Try
            Dim ns As XNamespace = "urn:Microsoft.Search.Response"
            Me.lblTotalRows.Content = resultsXmlDoc.Element(ns + "ResponsePacket").Element(ns + "Response").Element(ns + "Range").Element(ns + "TotalAvailable").Value
            Me.lblIsTotalRowsExact.Content = "N/A"
            Me.lblElapsedTime.Content = "N/A"

            Me.btnQueryNext.Content = "Query Next " & _countResults
            btnQueryNext.IsEnabled = True

            _intEndResultsShowing = CInt(_startAt) + CInt(_countResults) - 1
            Dim showingResults As String = _startAt & " - " & CStr(_intEndResultsShowing)
            Me.lblShowingResults.Content = showingResults

            ResultsWindow.Title = "ResultsWindow " & "ShowingResults: " & showingResults

        Catch ex As Exception

        End Try

    End Sub

    Public Sub SetResultsWinProperties_QueryEx(ByVal queryXml As String, ByVal ds As DataSet)

        Try

            _resultsDS = ds
            _wsQueryType = WSQueryType.QueryEx
            Me.txtResultsXml.Text = ds.GetXml()

            Dim queryXDoc As XDocument = XDocument.Load(New StringReader(queryXml))
            _startAt = queryXDoc.Element("QueryPacket").Element("Query").Element("Range").Element("StartAt").Value
            _countResults = queryXDoc.Element("QueryPacket").Element("Query").Element("Range").Element("Count").Value

            'Format the query
            Me.txtQuery.Text = queryXDoc.ToString()
            _query = queryXDoc.ToString()

            Me.btnQueryNext.Content = "Query Next " & _countResults


            _intEndResultsShowing = CInt(_startAt) + CInt(_countResults) - 1

            Dim showingResults As String = _startAt & " - " & CStr(_intEndResultsShowing)
            Me.lblShowingResults.Content = showingResults

            Dim extendedProps As System.Data.PropertyCollection = _resultsDS.ExtendedProperties
            Dim queryTerms As String = extendedProps("QueryTerms")
            Dim spellingSuggestion As String = extendedProps("SpellingSuggestion")
            Dim elapsedTime As String = extendedProps("ElapsedTime")
            Dim intElapsedTime As Double = CInt(elapsedTime) / 1000
            Dim keyword As String = extendedProps("Keyword")
            Dim definition As String = extendedProps("Definition")
            Dim queryModification As String = extendedProps("QueryModification")

            Me.lblQueryTerms.Content = queryTerms
            Me.lblElapsedTime.Content = CStr(intElapsedTime) & " seconds"
            Me.lblKeyword.Content = keyword
            Me.lblDefinition.Content = definition
            Me.lblQueryModification.Content = queryModification

            If ds.Tables("RelevantResults") IsNot Nothing Then
                Me.dgRelevantResults.DataContext = ds.Tables("RelevantResults")

                Dim rrExtendedProps As System.Data.PropertyCollection = ds.Tables("RelevantResults").ExtendedProperties

                Dim totalRows As String = rrExtendedProps("TotalRows")
                _numTotalResults = totalRows
                Dim isTotalRowsExact As String = rrExtendedProps("IsTotalRowsExact")

                Me.lblTotalRows.Content = totalRows.Trim()
                Me.lblIsTotalRowsExact.Content = isTotalRowsExact

                If _intEndResultsShowing < CInt(totalRows) Then
                    btnQueryNext.IsEnabled = True
                End If


            End If

            If ds.Tables("RefinementResults") IsNot Nothing Then

                Dim dc As DataColumn = New DataColumn("AddRefinement", GetType(System.Boolean))
                dc.DefaultValue = False
                ds.Tables("RefinementResults").Columns.Add(dc)

                Me.dgRefiner.DataContext = ds.Tables("RefinementResults")
            End If

            If ds.Tables("VisualBestBetsResults") IsNot Nothing Then
                Me.dgVBB.DataContext = ds.Tables("VisualBestBetsResults")
            End If

            If ds.Tables("SpecialTermResults") IsNot Nothing Then
                Me.dgSpecialTermResults.DataContext = ds.Tables("SpecialTermResults")
            End If

            Dim tempFile As String = String.Empty
            tempFile = Path.ChangeExtension(Path.GetTempFileName(), "xml")

            Dim resultsXmlDoc As New XmlDocument
            resultsXmlDoc.LoadXml(ds.GetXml)
            resultsXmlDoc.Save(tempFile)

            ieXML.Navigate(New Uri(tempFile))

            ResultsWindow.Title = "ResultsWindow " & "QueryTerms: " & queryTerms & " ShowingResults: " & showingResults

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

    End Sub




    Public Sub SetXml(ByVal resultsXmlString As String)
        Dim tempFile As String = String.Empty
        tempFile = Path.ChangeExtension(Path.GetTempFileName(), "xml")

        Dim resultsXmlDoc As New XmlDocument
        resultsXmlDoc.LoadXml(resultsXmlString)
        resultsXmlDoc.Save(tempFile)

        ieXML.Navigate(New Uri(tempFile))

    End Sub


    Private _query As String
    Public Property Query() As String
        Get
            Return _query
        End Get
        Set(ByVal value As String)
            _query = value
            Me.txtQuery.Text = value
        End Set
    End Property

    Private Sub btnCopyToClipboard_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnCopyToClipboard.Click

        ApplicationCommands.Copy.Execute(Me.dgRelevantResults.SelectedCells, Me.dgRelevantResults)

    End Sub


    Private Sub btnSaveFile_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnSaveFile.Click
        ' Configure save file dialog box
        Dim dlg As New Microsoft.Win32.SaveFileDialog()

        dlg.FileName = "Results"
        ' Default file name
        dlg.DefaultExt = ".xml"
        ' Default file extension
        dlg.Filter = "Results XML|*.xml"
        ' Filter files by extension
        ' Show save file dialog box
        Dim result As Nullable(Of Boolean) = dlg.ShowDialog()

        ' Process save file dialog box results
        If result = True Then
            ' Save document
            Dim filename As String = dlg.FileName
            _resultsDS.WriteXml(filename)
        End If

    End Sub

    Private Sub dgRefiner_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles dgRefiner.SelectionChanged

    End Sub

    Private Sub btnAddToRefinements_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddToRefinements.Click

        Try

            'Cycle Through the Refiners to see if something is checked and add to the query
            Dim dt As DataTable = DirectCast(Me.dgRefiner.DataContext, DataTable)
            Dim refinerXDoc As XDocument = XDocument.Load(New StringReader(dt.DataSet.GetXml()))

            'Add Additional Properties
            Dim refinerElements As IEnumerable(Of XElement) =
                From cp In refinerXDoc.Descendants("RefinementResults") _
                Where cp.Element("AddRefinement").Value = True _
                Select cp

            'Add RefinerTokens to Query
            If refinerElements.Count > 0 Then

                'Get the current query
                Dim queryXmlString As String = Me.txtQuery.Text

                Dim queryXDoc As XDocument = XDocument.Load(New StringReader(queryXmlString))

                'Add <RefinementFilters> Element if it does not exist in the query
                If queryXDoc.Element("QueryPacket").Element("Query").Element("RefinementFilters") Is Nothing Then
                    Dim re As XElement = New XElement("RefinementFilters")
                    queryXDoc.Element("QueryPacket").Element("Query").Add(re)
                End If

                For Each refinerElement As XElement In refinerElements
                    Dim tokenString As String
                    tokenString = refinerElement.Element("RefinementToken").Value

                    Dim tokenElement As New XElement("RefinementFilter", tokenString)
                    queryXDoc.Element("QueryPacket").Element("Query").Element("RefinementFilters").Add(tokenElement)
                Next

                Me.txtQuery.Text = queryXDoc.ToString()

            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

    End Sub

    Private Sub brnRerunQuery_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles brnRerunQuery.Click
        InitWS()

        Me.Cursor = Cursors.Wait

        Try

            Dim queryText As String = Me.txtQuery.Text
            Dim resultsWin As ResultsWindow

            If _wsQueryType = WSQueryType.Query Then
                Dim resultsXmlString As String = _SearchService.Query(queryText)

                resultsWin = New ResultsWindow
                resultsWin.SetResultsWinProperties_Query(queryText, resultsXmlString)

            Else
                Dim resultsDS As DataSet = _SearchService.QueryEx(queryText)
                resultsWin = New ResultsWindow
                resultsWin.SetResultsWinProperties_QueryEx(queryText, resultsDS)

            End If

            resultsWin.Username = _username
            resultsWin.Password = _password
            resultsWin.Domain = _domain
            resultsWin.WebserviceUrl = _url

            resultsWin.Show()

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

        Me.Cursor = Cursors.Arrow
    End Sub

    Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded

    End Sub

    Private Sub InitWS()
        Dim creds As New System.Net.NetworkCredential(_username, _password, _domain)

        Dim site As String = Me._url.Trim()
        If site.EndsWith("/") Then
            site = site + "_vti_bin/search.asmx"
        Else
            site = site + "/_vti_bin/search.asmx"
        End If

        _SearchService = New SearchService.QueryService
        _SearchService.Url = site
        _SearchService.PreAuthenticate = True
        _SearchService.UseDefaultCredentials = False
        _SearchService.Credentials = creds

    End Sub

    Private Sub btnSaveQuery_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnSaveQuery.Click

        Try

            ' Configure save file dialog box
            Dim dlg As New Microsoft.Win32.SaveFileDialog()

            dlg.FileName = "Query"
            ' Default file name
            dlg.DefaultExt = ".xml"
            ' Default file extension
            dlg.Filter = "Results XML|*.xml"
            ' Filter files by extension
            ' Show save file dialog box
            Dim result As Nullable(Of Boolean) = dlg.ShowDialog()

            ' Process save file dialog box results
            If result = True Then
                ' Save document
                Dim filename As String = dlg.FileName
                Dim xDoc As New XmlDocument
                xDoc.LoadXml(Me.txtQuery.Text)
                xDoc.Save(filename)
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

    End Sub

    Private Sub btnQueryNext_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnQueryNext.Click
        InitWS()

        Me.Cursor = Cursors.Wait

        Try

            Dim xDoc As New XmlDocument
            xDoc.LoadXml(_query)
            Dim newStartAt As Integer = Me._intEndResultsShowing + 1
            xDoc.SelectSingleNode("//StartAt").InnerText = CStr(newStartAt)

            Dim queryText As String = xDoc.OuterXml

            Dim resultsWin As New ResultsWindow

            If _wsQueryType = WSQueryType.Query Then
                Dim resultsXmlString As String = _SearchService.Query(queryText)
                resultsWin.SetResultsWinProperties_Query(queryText, resultsXmlString)
            ElseIf _wsQueryType = WSQueryType.QueryEx Then
                Dim resultsDS As DataSet = _SearchService.QueryEx(queryText)
                resultsWin.SetResultsWinProperties_QueryEx(queryText, resultsDS)
            End If

            resultsWin.Username = _username
            resultsWin.Password = _password
            resultsWin.Domain = _domain
            resultsWin.WebserviceUrl = _url
            resultsWin.Show()

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

        Me.Cursor = Cursors.Arrow
    End Sub

 

    Private Enum WSQueryType
        Query
        QueryEx
    End Enum


 
    Private Sub btnSaveAllResults_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnSaveAllResults.Click

        Me.Cursor = Cursors.Wait

        Try

            Dim queryText As String = Me.txtQuery.Text

            Dim saveresultsWin As New SaveAllResultsWindow
            'saveresultsWin.SetResultsWinProperties_QueryEx(queryText, resultsDS)
            'resultsWin.Query = queryText
            saveresultsWin.Username = _username
            saveresultsWin.Password = _password
            saveresultsWin.Domain = _domain
            saveresultsWin.Query = _query
            saveresultsWin.NumTotalResults = _numTotalResults

            saveresultsWin.WebserviceUrl = _url

            saveresultsWin.Show()

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

        Me.Cursor = Cursors.Arrow
    End Sub
End Class


